package com.hbut.friend.service.user.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.hbut.common.core.constants.Constants;
import com.hbut.common.core.domain.TableDataInfo;
import com.hbut.common.core.enums.ExamListType;
import com.hbut.common.core.enums.ResultCode;
import com.hbut.common.core.utils.ThreadLocalUtil;
import com.hbut.common.security.exception.ServiceException;
import com.hbut.common.security.service.TokenService;
import com.hbut.friend.domain.exam.Exam;
import com.hbut.friend.domain.exam.dto.ExamQueryDTO;
import com.hbut.friend.domain.exam.vo.ExamVO;
import com.hbut.friend.domain.user.UserExam;
import com.hbut.friend.manager.ExamCacheManager;
import com.hbut.friend.mapper.exam.ExamMapper;
import com.hbut.friend.mapper.user.UserExamMapper;
import com.hbut.friend.service.user.IUserExamService;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserExamServiceImp implements IUserExamService {
    @Autowired
    private UserExamMapper userExamMapper;
    @Autowired
    private ExamMapper examMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ExamCacheManager examCacheManager;
//    @Value("${jwt.secret}")
//    private String secret;

    @Override
    public int enter(String token, String examId) {
        Exam exam = examMapper.selectById(examId);
        if(exam == null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        if(exam.getStartTime().isBefore(LocalDateTime.now())){
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
//        Long userId = tokenService.getUserId(token, secret);
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, exam.getExamId())
                .eq(UserExam::getUserId, userId));
        if(userExam != null) {
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTERED);
        }
        //redis中添加用户报名记录
        examCacheManager.addUserExamCache(userId, exam.getExamId());
        //数据库中添加用户报名记录
        userExam = new UserExam();
        userExam.setUserId(userId);
        userExam.setExamId(exam.getExamId());
        int insert = userExamMapper.insert(userExam);
        return insert;
    }

    @Override
    public TableDataInfo list(ExamQueryDTO questionQueryDTO) {
        //从redis中获取 竞赛列表的数据
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        questionQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        Long total = examCacheManager.getListSize(questionQueryDTO.getType(), userId);
        List<ExamVO> examVOList;
        // 如果redis中没有数据或者数据量为0
        if(total == null || total <= 0){
            // 分页查询
            PageHelper.startPage(questionQueryDTO.getPageNum(), questionQueryDTO.getPageSize());
            // 从数据库中获取竞赛列表
            examVOList = userExamMapper.selectUserExamList(userId);
            //将数据存入redis中
            examCacheManager.refreshCache(questionQueryDTO.getType(),userId);
        }else{
            // 从redis中获取竞赛列表
            examVOList = examCacheManager.getExamVOList(questionQueryDTO,userId);
            // 更新总数
            //total = new PageInfo<>(examVOList).getTotal();
            total = examCacheManager.getListSize(questionQueryDTO.getType(),userId);
        }
        // 如果竞赛列表为空
        if(Collections.isEmpty(examVOList)){
            return TableDataInfo.empty();
        }
        // 返回竞赛列表和总数
        return TableDataInfo.success(examVOList, total);
    }
}
